package com.superme.content.controller;


import com.sun.management.OperatingSystemMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;

@Slf4j
@RestController("cpu")
public class CpuStateLinuxController {

    @GetMapping("state")
    public String Status() {
        try {
            OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

            // 获取CPU使用率
            double cpuUsage = osBean.getSystemCpuLoad() * 100;
            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            String cpuValue = decimalFormat.format(cpuUsage);
            log.info("CPU使用率: {}%", cpuValue);

            // 执行系统命令
            Process process = Runtime.getRuntime().exec("free -b");
            // 获取命令输出流
            InputStream inputStream = process.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 解析输出数据
                if (line.startsWith("Mem:")) {
                    log.info("line:{}", line);
                    String[] split = line.split("\\s+");
                    long totalMemory = Long.parseLong(split[1]);
                    // 获取可用的内存信息
                    long avaMemory = Long.parseLong(split[6]);
                    // 获取内存使用率
                    double memoryUsage = (double) (totalMemory - avaMemory) / totalMemory * 100;
                    String memoryValue = decimalFormat.format(memoryUsage);
                    log.info("内存使用率: {}%", memoryValue);
                }
            }

            //获取连接数
            // 执行系统命令
            Process connprocess = Runtime.getRuntime().exec("netstat -an | grep ESTABLISHED |grep -v 127.0.0.1|wc -l");

            // 获取命令输出流
            InputStream conninputStream = connprocess.getInputStream();
            BufferedReader connbufferedReader = new BufferedReader(new InputStreamReader(conninputStream));

            connbufferedReader.readLine();
            connbufferedReader.readLine();
            // 读取命令输出结果
            String connLine;
            int connectionCount = 0;
            while ((connLine = connbufferedReader.readLine()) != null) {
                if (connLine.contains("ESTABLISHED") && !connLine.contains("127.0.0.1")) {
                    connectionCount++;
                }
            }
            log.info("Connection Count: {}", connectionCount);

            ProcessBuilder processBuilder = new ProcessBuilder("df", "-h");
            Process diskprocess = processBuilder.start();
            // 读取命令输出
            BufferedReader diskReader = new BufferedReader(new InputStreamReader(diskprocess.getInputStream()));
            String diskline;
            double totalSize = 0;
            double useSize = 0;
            while ((diskline = diskReader.readLine()) != null) {
                if (diskline.startsWith("/dev/")) {
                    String[] parts = diskline.split("\\s+");
                    String filesystem = parts[0];
                    double size = convertToMB(parts[1]);
                    double use = convertToMB(parts[2]);

                    totalSize += size;
                    useSize += use;

                }
            }
            // 获取内存使用率
            double diskUsage = (double) useSize / totalSize * 100;
            String diskValue = decimalFormat.format(diskUsage);
            log.info(" diskPercent: {}%", diskValue);
            log.info("总磁盘大小: {}MB", totalSize);
            log.info("已使用磁盘大小: {}MB", useSize);
            log.info("磁盘使用率: {}%", diskValue);

            // 关闭流
            bufferedReader.close();
            connbufferedReader.close();
            inputStream.close();
            // 等待命令执行完成
            process.waitFor();
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
            log.info("获取设备状态信息失败。{}", e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "ok";
    }


    private static double convertToMB(String sizeString) {
        double size = 0.0;

        // 提取数字和单位
        String numberPart = sizeString.replaceAll("[^0-9.]", "");
        String unitPart = sizeString.replaceAll("[0-9.]", "");

        // 根据单位进行转换
        if (unitPart.equalsIgnoreCase("G")) {
            size = Double.parseDouble(numberPart) * 1024;
        } else if (unitPart.equalsIgnoreCase("M")) {
            size = Double.parseDouble(numberPart);
        } else if (unitPart.equalsIgnoreCase("K")) {
            size = Double.parseDouble(numberPart) / 1024;
        }

        return size;
    }
}
